package issuebackup;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.text.BadLocationException;

import test.IO.Output;
import test.Issue.Issue;
import test.config.Config;
import test.workflow.Flow;
import test.workflow.Statuses;

public class Main {

	public static String flowStatus = Statuses.LOGIN_NEEDED;
	public static List<Issue> issues = new ArrayList<Issue>();
	public static Issue actualIssue;
	static String startPorgressAnchorHREF;

	/**
	 * @param args
	 * @throws IOException
	 * @throws FileNotFoundException
	 * @throws BadLocationException
	 */
	public static void main(String[] args) throws FileNotFoundException,
			IOException, BadLocationException {
		test.Main.initConfig();

		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Output.log(formatter.format(new Date()));
		Output.log("Reading config file.");

		if (flowStatus.equals(Statuses.LOGIN_NEEDED)) {
			Output.log("Logging in.");

			Flow.login(Config.getJiraUrl(), Config.getJiraUsername(), Config
					.getJiraPassword());
			flowStatus = Statuses.SEARCH_FOR_PRIORITY_ISSUES;
		}

		if (flowStatus.equals(Statuses.SEARCH_FOR_PRIORITY_ISSUES)) {
			Output.log("Searching for issues.");
			issues = Flow.searchForPriorityIssuesToProcess(Config
					.getJiraIssueFilterURL(), false);

			if (issues != null && issues.size() > 0) {
				Output.log("Issues:");
				for (Issue issue : issues) {
					Output.log(issue.toString());
				}
				flowStatus = Statuses.OPEN_ISSUE;
			} else {
				Output.log("No issue have found!");
			}
		}

		if (flowStatus.equals(Statuses.OPEN_ISSUE)) {
			for (Issue actualIssue : issues) {
				Output.log("Opening issue:");
				Output.log(actualIssue.toString());

				InputStream openIssueInputStream = Flow.openIssue(Config
						.getJiraUrl()
						+ "browse/", actualIssue.getId());

				String filename = Config.getTmpFilePath() + actualIssue.getId()
						+ ".html";

				Output.log("Saving issue text to file: " + filename);
				String issueText = Output
						.inputStreamToString(openIssueInputStream);
				Output.toFile(filename, issueText, false);

			}

		}

	}

}
